package untils

import (
	"fmt"
	"learn-srv/basic/config"
	"time"
)

// 同步库存
func SyncCourseStock(courseId, stock int) {
	key := fmt.Sprintf("courserId:%d", courseId)
	for i := 0; i < stock; i++ {
		config.Rdb.LPush(config.Ctx, key, stock)
	}
}

// 获取库存
func GetCourseStock(courseId int) int {
	key := fmt.Sprintf("courserId:%d", courseId)
	stock, err := config.Rdb.LLen(config.Ctx, key).Result()
	if err != nil {
		return 0
	}
	return int(stock)
}

// 扣减redsi库存
func DeleteCourseStock(courseId int) bool {
	key := fmt.Sprintf("courserId:%d", courseId)
	result, err := config.Rdb.LPop(config.Ctx, key).Result()
	if err != nil {
		return false
	}
	return result == "1"
}

// 添加分布式锁
func LockCourseStock(orderId int) bool {
	key := fmt.Sprintf("orderId:%d", orderId)
	_, err := config.Rdb.SetNX(config.Ctx, key, 1, time.Minute*10).Result()
	if err != nil {
		return false
	}
	return true
}

// 删除分布式锁
func UnLockCourseStock(orderId int) bool {
	key := fmt.Sprintf("orderId:%d", orderId)
	_, err := config.Rdb.Del(config.Ctx, key).Result()
	if err != nil {
		return false
	}
	return true
}
